/** @format */

const { Controller } = require("egg");

class TaskController extends Controller {
    async index() {
        const { ctx, app } = this;
    }
    async addtask() {
        const { ctx, app } = this;
        let clientdata = ctx.request.body;
        console.log(clientdata, "前端传参");
        // 插入数据库
        const result = await this.app.mysql.insert("tasks", {
            task_name: clientdata.task_name,
            task_type: clientdata.task_type,
            expirationtime: clientdata.expirationtime,
            task_detail: clientdata.task_detail,
            team_id: clientdata.team_id,
            status: "未发布",
            create_id: clientdata.create_id,
        }); // 在 posts 表中，插入 title 为 Hello World 的记录
        if (result) {
            ctx.body = {
                code: 200,
                desp: "添加成功",
                data: result,
            };
        } else {
            ctx.body = {
                code: 201,
                desp: "添加失败",
            };
        }
    }
    async gettasklist() {
        const { ctx, app } = this;
        let userinfo = null;
        let myarrayteam = [];
        let clientdata = ctx.request.body;
        try {
            userinfo = app.jwt.verify(ctx.request.header.token, app.config.jwt.secret);
            console.log(userinfo, "我是用户");
            let data2 = {
                // 搜索 posts 表
                where: { member_id: userinfo.userid }, // WHERE 条件
            };
            let team_members = await this.app.mysql.select("team_members", data2);
            console.log(team_members, "team_membersteam_members");
            myarrayteam = team_members.map((item) => {
                return item.team_id;
            });
            console.log(myarrayteam, "myarrayteam");
            // console.log(post, 'post')
        } catch (error) {
            console.error(error);
            userinfo = false;
            // Expected output: ReferenceError: nonExistentFunction is not defined
            // (Note: the exact output may be browser-dependent)
        }
        console.log(myarrayteam, "myarrayteam");

        // let data = {
        //     // 搜索 posts 表
        //     where: {
        //         ...(clientdata.Query ? clientdata.Query : ""),
        //         team_id: myarrayteam,
        //     }, // WHERE 条件
        //     limit: clientdata.pagesize, // 返回数据量
        //     offset: (clientdata.pageindex - 1) * clientdata.pagesize, // 数据偏移量
        //     orders: [["id"]], // 排序方式
        // };
        // let tasklist = await this.app.mysql.select("tasks", data);
        let tasklist = clientdata.Query
            ? await app.mysql.query(`SELECT * FROM tasks  WHERE ${clientdata.Query} and team_id in (${myarrayteam.join(",")})`)
            : await app.mysql.query(`SELECT * FROM tasks  `);
        let obj = JSON.stringify(tasklist[0]);
        console.log(obj, "obkj");
        await Promise.all(
            tasklist.map(async (item, index) => {
                let team = await this.app.mysql.select("volunteer_team", {
                    where: { team_id: item.team_id },
                });
                tasklist[index].team = team[0];
                let createinfo = await this.app.mysql.get("userinfo", {
                    id: item.create_id,
                });
                tasklist[index].createinfo = createinfo;

                let data = {
                    // 搜索 posts 表
                    where: {
                        task_id: item.id,
                    }, // WHERE 条件
                };
                let tasklog = await this.app.mysql.select("tasks_log", data);
                await Promise.all(
                    tasklog.map(async (item, index) => {
                        let executor = await this.app.mysql.get("userinfo", {
                            id: item.executor,
                        });
                        tasklog[index].executor = executor;
                        tasklog[index].taskinfo = obj;
                    }),
                );
                tasklist[index].tasklog = tasklog;
            }),
        );
        tasklist[0].tasklog.map((item, index) => {
            tasklist[0].tasklog[index].taskinfo = JSON.stringify(tasklist[0]);
        });

        if (tasklist) {
            ctx.body = {
                data: tasklist,
                desp: "获取成功",
                code: 200,
            };
        } else {
            ctx.body = {
                desp: "获取失败",
                code: 201,
            };
        }
    }
    // 发布任务
    async publishtask() {
        const { ctx, app } = this;
        let clientdata = ctx.request.body;
        clientdata.executor.forEach(async (el) => {
            await this.app.mysql.insert("tasks_log", {
                executor: el,
                task_id: clientdata.task_id,
                task_type: clientdata.task_type,
            }); // 在 posts 表中，插入 title 为 Hello World 的记录
        });
        const row2 = {
            status: "已发布",
        };
        const options = {
            where: {
                id: clientdata.task_id,
            },
        };
        const result2 = await this.app.mysql.update("tasks", row2, options); // 更新 posts 表中的记录
        if (clientdata.coordinate) {
            const row2 = {
                coordinate: clientdata.coordinate,
                expire: clientdata.expire,
                status: "已发布",
            };
            const options = {
                where: {
                    id: clientdata.task_id,
                },
            };
            const result2 = await this.app.mysql.update("tasks", row2, options); // 更新 posts 表中的记录
        }
        ctx.body = {
            code: 200,
            desp: "发布成功",
        };

        // tasks_log
    }
    async getmy_tasklist() {
        const { ctx, app } = this;
        let userinfo = null;
        let mytask = [];
        let clientdata = ctx.request.body;
        try {
            userinfo = app.jwt.verify(ctx.request.header.token, app.config.jwt.secret);
            console.log(userinfo, "我是用户");
            let data = {
                // 搜索 posts 表
                where: { ...(clientdata.Query ? clientdata.Query : ""), executor: userinfo.userid }, // WHERE 条件
            };
            mytask = await this.app.mysql.select("tasks_log", data);
            console.log(mytask, "team_membersteam_members");
            await Promise.all(
                mytask.map(async (item, index) => {
                    let taskinfo = await this.app.mysql.select("tasks", {
                        where: { id: item.task_id },
                    });
                    mytask[index].taskinfo = taskinfo[0];
                    let team = await this.app.mysql.select("volunteer_team", {
                        where: { team_id: taskinfo[0].team_id },
                    });
                    mytask[index].team = team[0];

                    let createinfo = await this.app.mysql.get("userinfo", {
                        id: taskinfo[0].create_id,
                    });
                    mytask[index].createinfo = createinfo;
                }),
            );
        } catch (error) {
            console.error(error);
            userinfo = false;
            // Expected output: ReferenceError: nonExistentFunction is not defined
            // (Note: the exact output may be browser-dependent)
        }
        ctx.body = {
            data: mytask,
            desp: "查询成功",
            code: 200,
        };
    }
    // 提交任务
    async sumbittask() {
        const { ctx, app } = this;
        let clientdata = ctx.request.body;
        let task_status = "进行中";
        clientdata.task_file = JSON.stringify(clientdata.task_file);
        if (clientdata.task_progress == 100) {
            task_status = "已完成";
        }
        const row2 = {
            task_anger: clientdata.task_anger,
            task_status: task_status,
            task_file: clientdata.task_file,
            task_progress: clientdata.task_progress,
        };
        const options = {
            where: {
                id: clientdata.id,
            },
        };
        const result2 = await this.app.mysql.update("tasks_log", row2, options); // 更新 posts 表中的记录
        if (result2) {
            ctx.body = {
                code: 200,
                desp: "提交成功",
            };
        } else {
            ctx.body = {
                code: 201,
                desp: "提交失败",
            };
        }
    }
    async getanserlog() {
        const { ctx, app } = this;
        let userinfo = null;
        let myarrayteam = [];
        let clientdata = ctx.request.body;
        try {
            userinfo = app.jwt.verify(ctx.request.header.token, app.config.jwt.secret);
            console.log(userinfo, "我是用户");
            let data2 = {
                // 搜索 posts 表
                where: { member_id: userinfo.userid }, // WHERE 条件
            };
            let team_members = await this.app.mysql.select("team_members", data2);
            console.log(team_members, "team_membersteam_members");
            myarrayteam = team_members.map((item) => {
                return item.team_id;
            });
            console.log(myarrayteam, "myarrayteam");
            // console.log(post, 'post')
        } catch (error) {
            console.error(error);
            userinfo = false;
            // Expected output: ReferenceError: nonExistentFunction is not defined
            // (Note: the exact output may be browser-dependent)
        }
        console.log(myarrayteam, "myarrayteam");

        let data = {
            // 搜索 posts 表
            where: {
                team_id: myarrayteam,
            }, // WHERE 条件
            limit: clientdata.pagesize, // 返回数据量
            offset: (clientdata.pageindex - 1) * clientdata.pagesize, // 数据偏移量
            orders: [["id"]], // 排序方式
        };
        console.log(data, "data");
        let taskloglist = await this.app.mysql.select("tasks", data);
        let anserloglist = [];
        await Promise.all(
            taskloglist.map(async (item, index) => {
                let tasklogminlist = await this.app.mysql.select("tasks_log", { where: { task_id: item.id } });
                console.log(tasklogminlist, "tasklogminlist");
                anserloglist = [...tasklogminlist];
            }),
        );
        await Promise.all(
            anserloglist.map(async (item, index) => {
                let executorinfo = await this.app.mysql.get("userinfo", { id: item.executor });
                anserloglist[index].executorinfo = executorinfo;
                let taskinfo = await this.app.mysql.get("tasks", { id: item.task_id });
                let creatinfo = await this.app.mysql.get("userinfo", { id: taskinfo.create_id });
                taskinfo.creatinfo = creatinfo;
                let teaminfo = await this.app.mysql.get("volunteer_team", { team_id: taskinfo.team_id });
                console.log(teaminfo, "teaminfoteaminfoteaminfoteaminfoteaminfoteaminfo");
                taskinfo.teaminfo = teaminfo;
                anserloglist[index].taskinfo = taskinfo;
            }),
        );

        console.log(taskloglist, "taskloglist");
        if (anserloglist) {
            ctx.body = {
                data: anserloglist,
                desp: "获取成功",
                code: 200,
            };
        } else {
            ctx.body = {
                desp: "获取失败",
                code: 201,
            };
        }
    }
    async getanserloglist() {
        const { ctx, app } = this;
        let clientdata = ctx.request.body;

        let anserloglist = await this.app.mysql.select("tasks_log", { where: clientdata.Query });

        await Promise.all(
            anserloglist.map(async (item, index) => {
                let executorinfo = await this.app.mysql.get("userinfo", { id: item.executor });
                anserloglist[index].executorinfo = executorinfo;
                let taskinfo = await this.app.mysql.get("tasks", { id: item.task_id });
                let creatinfo = await this.app.mysql.get("userinfo", { id: taskinfo.create_id });
                taskinfo.creatinfo = creatinfo;
                let teaminfo = await this.app.mysql.get("volunteer_team", { team_id: taskinfo.team_id });
                console.log(teaminfo, "teaminfoteaminfoteaminfoteaminfoteaminfoteaminfo");
                taskinfo.teaminfo = teaminfo;
                anserloglist[index].taskinfo = taskinfo;
            }),
        );

        console.log(anserloglist, "taskloglist");
        if (anserloglist) {
            ctx.body = {
                data: anserloglist,
                desp: "获取成功",
                code: 200,
            };
        } else {
            ctx.body = {
                desp: "获取失败",
                code: 201,
            };
        }
    }
    async getanserlogdetail() {
        const { ctx, app } = this;
        let clientdata = ctx.request.body;
        let data = {
            // 搜索 posts 表
            where: {
                ...(clientdata.Query ? clientdata.Query : ""),
            }, // WHERE 条件
            limit: clientdata.pagesize, // 返回数据量
            offset: (clientdata.pageindex - 1) * clientdata.pagesize, // 数据偏移量
            orders: [["id"]], // 排序方式
        };
        let taskloglist = await this.app.mysql.select("tasks_log", data);
        console.log(taskloglist, "taskloglisttaskloglisttaskloglist");
        // let anserloglist = [];

        await Promise.all(
            taskloglist.map(async (item, index) => {
                let executorinfo = await this.app.mysql.get("userinfo", { id: item.executor });
                taskloglist[index].executorinfo = executorinfo;
                let taskinfo = await this.app.mysql.get("tasks", { id: item.task_id });
                let creatinfo = await this.app.mysql.get("userinfo", { id: taskinfo.create_id });
                taskinfo.creatinfo = creatinfo;
                let teaminfo = await this.app.mysql.get("volunteer_team", { team_id: taskinfo.team_id });
                console.log(teaminfo, "teaminfoteaminfoteaminfoteaminfoteaminfoteaminfo");
                taskinfo.teaminfo = teaminfo;
                taskloglist[index].taskinfo = taskinfo;
            }),
        );

        if (taskloglist) {
            ctx.body = {
                data: taskloglist,
                desp: "获取成功",
                code: 200,
            };
        } else {
            ctx.body = {
                desp: "获取失败",
                code: 201,
            };
        }
    }
    async getchecktask() {
        const { ctx, app } = this;
        let clientdata = ctx.request.body;
        let data = {
            // 搜索 posts 表
            where: {
                ...clientdata,
            }, // WHERE 条件
        };
        console.log(data, "data");
        let taskloglist = await this.app.mysql.select("tasks_log", data);
        console.log(taskloglist, "taskloglist");
        await Promise.all(
            taskloglist.map(async (item, index) => {
                let taskinfo = await this.app.mysql.get("tasks", { id: item.task_id });
                taskloglist[index].taskinfo = taskinfo;

                taskloglist[index].taskinfo.coordinate = JSON.parse(taskinfo.coordinate);

                let overdue = "未过期";
                let data = new Date(taskinfo.expire);
                let nowdata = new Date();
                if (data < nowdata) {
                    overdue = "已过期";
                }
                taskloglist[index].overdue = overdue;
                // taskinfo.expire = taskinfo.expire + "";
                // taskloglist[index].taskinfo.expire = taskinfo.expire.split("T")[0] + taskinfo.expire.split("T")[1].split(".")[0];
            }),
        );
        console.log(taskloglist, "taskloglist");
        ctx.body = {
            data: taskloglist,
            desp: "获取成功",
            code: 200,
        };
    }
    async finshchecktask() {
        const { ctx, app } = this;
        let clientdata = ctx.request.body;
        let date = new Date();
        let anser = JSON.stringify({ posation: clientdata.task_address, time: date });
        const row2 = {
            task_progress: 100,
            task_status: "已完成",
            task_anger: anser,
        };
        const options = {
            where: {
                id: clientdata.task_id,
            },
        };
        const result2 = await this.app.mysql.update("tasks_log", row2, options); // 更新 posts 表中的记录
        console.log(clientdata);
        ctx.body = {
            desp: "签到成功",
            code: 200,
        };
    }
}
module.exports = TaskController;
